import java.util.Arrays;

/**
* Created with IntelliJ IDEA.
* Description:
* User: 86183
* Date: 2022-11-01
* Time: 8:37
*/
public class Test {
    public static void main(String[] args) {
        int[]array = {23,45,67,12,34,27,56,1};
//        megerSort(array);
        quickSort(array);
        System.out.println(Arrays.toString(array));
    }

    private static void quickSort(int[] array) {
        quick(array,0,array.length-1);
    }

    private static void quick(int[] array, int left, int right) {
        if(left >= right){
            return;
        }
        int povit = Hare(array,left,right);
        quick(array,left,povit-1);
        quick(array,povit+1,right);
    }

    private static int Hare(int[] array, int left, int right) {
        int i = left;
        int povit = array[left];
        while (left < right){
            while (left< right && array[right] >= povit){
                right --;
            }
            while (left < right && array[left] <= povit){
                left++;
            }
            swap(array,left,right);
        }
        swap(array,left,i);
        return left;
    }

    private static void swap(int[] array, int left, int right) {
        int tmp =array[left];
        array[left] = array[right];
        array[right] = tmp;
    }

    private static void megerSort(int[] array) {
        int gap = 1;
        while (gap < array.length){
            for (int i = 0; i < array.length; i+= gap*2) {
                int left = i;
                int mid = left + gap -1;
                int right = mid +gap;
                if(mid >= array.length){
                    mid =array.length-1;
                }
                if(right >= array.length-1){
                    right = array.length-1;
                }
                meger(array,left,mid,right);
            }
            gap *=2;
        }
    }

    private static void meger(int[] array, int left, int mid, int right) {
        int k = 0;
        int[] tmp = new int[right-left+1];
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        while (s1 <= e1 && s2 <= e2){
            if(array[s1] < array[s2]){
                tmp[k++] = array[s1++];
            }else {
                tmp[k++] = array[s2++];
            }
        }
        while (s1 <= e1){
            tmp[k++] = array[s1++];
        }
        while (s2 <= e2){
            tmp[k++] = array[s2++];
        }
        for (int i = 0; i < k; i++) {
            array[i+left] = tmp[i];
        }
    }
}